# coding=utf-8
import pecan_config
from wsgiref import simple_server
from pecan import make_app
from app.pecan_init.model import init_model
import logging

LOG = logging.getLogger()


def setup_app(config):
    init_model()
    app_conf = dict(config.app)

    return make_app(
        app_conf.pop('root'),
        logging=getattr(config, 'logging', {}),
        **app_conf
    )


def start_server():
    host, port = pecan_config.server['host'], int(pecan_config.server['port'])
    print('pecan service will start on http://{}:{}'.format(host, port))
    service = simple_server.make_server(host, port, setup_app(pecan_config))
    LOG.info('pecan service start success http://{}:{}'.format(host, port))
    try:
        service.serve_forever()
    except KeyboardInterrupt:
        service.shutdown()
    finally:
        service.server_close()
